package com.lxz.datasource.config.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class MultipleDateSourceConfig {

	@Bean("master")
	@ConfigurationProperties(prefix = "spring.datasource.master")
	public DataSource createMasterDataSource() {
		return new DruidDataSource();
	}

	@Bean("slave")
	@ConfigurationProperties(prefix = "spring.datasource.slave")
	public DataSource createSlave1DataSource() {
		return new DruidDataSource();
	}

	/**
	 * 设置动态数据源，通过@Primary 来确定主DataSource
	 */
	@Bean
	@Primary
	public DataSource createDynamicdataSource(@Qualifier("master") DataSource master,
			@Qualifier("slave") DataSource slave) {
		DynamicDataSource dynamicDataSource = new DynamicDataSource();
		// 设置默认数据源
		dynamicDataSource.setDefaultTargetDataSource(master);
		// 配置多数据源
		Map<Object, Object> map = new HashMap<>();
		map.put("master", master);
		map.put("slave", slave);
		dynamicDataSource.setTargetDataSources(map);
		return dynamicDataSource;
	}

}
